#include "messageparser.h"

MessageParser::MessageParser(QObject *parent)
    : QObject(parent), mState(WAIT_START) {}

MessageParser::~MessageParser() {}

void MessageParser::unpack(const char *data) {
    for (int i = 0; data[i] != '\0'; i++) {
        char c = data[i];

        switch (mState) {
        case WAIT_START:
            if (c == START_MSG) {
                mState = IN_MESSAGE;
                mReceivedData.clear(); // 清空之前未完成的消息（如果有的话）
            }
            break;
        case IN_MESSAGE:
            if (c == END_MSG) {
                mState = WAIT_START;
                emit newData(mReceivedData.split(' '));
                mReceivedData.clear(); // 准备好接收下一条消息
            } else if (std::isdigit(c) || std::isspace(c) || c == '-' || c == '.') {
                mReceivedData.append(c);
            }
            break;
        default:
            break;
        }
    }
}
